package com.daxiong.commons;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ContainUtils {
    private static final String ENCODING = new String("UTF-8");
    private static final Logger LOGGER = LoggerFactory.getLogger(ContainUtils.class);

    /**
     * 將[來源資料夾]全部內容，依[目標文件副檔名]找到符合文件後查找是否有包含[搜尋內容]，最後回傳符合檔案物件清單.
     * 
     * @param sourceDirectory
     *            來源資料夾
     * @param extension
     *            目標文件副檔名
     * @param search
     *            搜尋內容
     * @return 符合檔案清單
     */
    public static List<File> execution(final File sourceDirectory, final String extension, final String search) {
        final List<File> accordList = new ArrayList<File>();

        // TODO 要判斷

        try {
            process(sourceDirectory, extension, search, accordList);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        return accordList;
    }

    private static boolean isContain(final File file, final String search) {
        boolean isContain = false;

        try {
            final List<?> lines = FileUtils.readLines(file, ENCODING);
            for (final Object object : lines) {
                final String line = StringUtils.trim((String) object);
                if (StringUtils.indexOf(line, search) != StringUtils.INDEX_NOT_FOUND) {
                    isContain = true;
                    break;
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        return isContain;
    }

    private static void process(final File file, final String extension, final String search, final List<File> list) {
        if (file.isDirectory()) {
            for (final File sub : file.listFiles()) {
                process(sub, extension, search, list);
            }
        } else {
            if (StringUtils.isBlank(extension)
                    || StringUtils.equals(extension, FilenameUtils.getExtension(file.getAbsolutePath()))) {
                if (isContain(file, search)) {
                    list.add(file);
                }
            }
        }
    }
}
